<?php

namespace Home\Model;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;
use Zend\Stdlib\DateTime;
use Zend\Session\Container;


class TintucTable extends AbstractTableGateway {

    protected $table = 'tintuc';

    public function __construct(Adapter $adapter) {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new Tintuc());

        $this->initialize();
    }

    public function fetchAll(Select $select = null) {
        if (null === $select)
            $select = new Select();
        $select->from($this->table,array('*'))
				->join(
					'nguoidung',
					'tintuc.tacgia = nguoidung.id',
					array('hoten'))
				->join(
					'chuyenmuc',
					'tintuc.chuyenmuc = chuyenmuc.id',
					array('tenchuyenmuc','duongdan'));
        $resultSet = $this->selectWith($select);
        $resultSet->buffer();
        return $resultSet;
    }
	public function getBaivietlienquan($id,$chuyenmuc) {
        $id = (string) $id;
		$chuyenmuc = (string) $chuyenmuc;
		$select = new Select();
        $select->from($this->table)->limit(5)
				->where(array('linkrutgon != "'.$id.'"','duongdan' => $chuyenmuc,'trangthai' => 'Hiển thị'))
				->join(
					'nguoidung',
					'tintuc.tacgia = nguoidung.id',
					array('hoten'))
				->join(
					'chuyenmuc',
					'tintuc.chuyenmuc = chuyenmuc.id',
					array('tenchuyenmuc'));
        $resultSet = $this->selectWith($select);
        $resultSet->buffer();
        return $resultSet;
    }
	public function getBaiviet($id) {
        $id = (string) $id;
		$select = new Select();
        $select->from($this->table)->limit(5)
				->where(array('linkrutgon' => $id))
				->join(
					'nguoidung',
					'tintuc.tacgia = nguoidung.id',
					array('hoten'))
				->join(
					'chuyenmuc',
					'tintuc.chuyenmuc = chuyenmuc.id',
					array('tenchuyenmuc'));
        $resultSet = $this->selectWith($select);
        
        $row = $resultSet->current(); 
        return $row;
    }
	

    public function getTintuc($id) {
        $id = (int) $id;
        $rowset = $this->select(array('id' => $id));
        $row = $rowset->current(); 
        return $row;
    }
	public function getView($linkrutgon)
	{
		$select = new Select();
        $select->from($this->table,array('*'))->where(array('linkrutgon'=>$linkrutgon));
        $resultSet = $this->selectWith($select);
        $resultSet->buffer();
		
    	$row = $resultSet->current();
        if($row)
		{
			$data = array(
				'soluotxem' => ($row->soluotxem)+1
			);
			$this->update($data, array('linkrutgon' => $linkrutgon));
		}
		
		
	}


}
